/*
 * @lc app=leetcode.cn id=99 lang=typescript
 *
 * [99] 恢复二叉搜索树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

/**
 Do not return anything, modify root in-place instead.
 */
function recoverTree(root: TreeNode | null): void {
  // 中序遍历，找到2组前面大于后面的组合
  let prev: TreeNode | null = null;
  let p: TreeNode | null = null;
  let q: TreeNode | null = null;
  // 中序遍历，找到需要交换的2个节点
  const inorder = (node: TreeNode | null) => {
    if (node === null) return;
    inorder(node.left);
    if (prev !== null && prev.val > node.val) {
      if (p === null) p = prev;
      q = node;
    }
    prev = node;
    inorder(node.right);
  };

  inorder(root);
  // 交换节点值
  let temp = p.val;
  p.val = q.val;
  q.val = temp;
}
// @lc code=end
